import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router, Params } from '@angular/router';

import 'rxjs/add/operator/switchMap';
import { Observable } from 'rxjs/Observable';

import { Home } from './home';
import { HomeService } from './home.service';

@Component({
  template: `
    <ul class="demo-list-icon mdl-list">
      <li class="mdl-list__item" *ngFor="let home of homeList | async"
        [class.selected]="isSelected(home)"
        (click)="onSelect(home)">
        <span class="mdl-list__item-primary-content">
          {{home.id}}
          {{home.name}}
        </span>
      </li>
    </ul>
    <router-outlet></router-outlet>
  `
})
export class HomeListComponent implements OnInit {
  public homeList: Observable<Home[]>;
  public selectedId: number;

  constructor(
    private service: HomeService,
    private route: ActivatedRoute,
    private router: Router) { }

  public ngOnInit() {
    this.homeList = this.route.params
      .switchMap((params: Params) => {
        this.selectedId = +params['id'];
        return this.service.getHomeList();
      });
  }

  public onSelect(home: Home) {
    this.selectedId = home.id;

    this.router.navigate([home.id], { relativeTo: this.route });
  }

  public isSelected(home: Home) {
    return home.id === this.selectedId;
  }

}
